﻿using FineUI;
using SysManage.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data.Models.Common;
using ZHDJ.WebPage;
using System.Data;
using System.Text;
using MySql.Data.MySqlClient;

namespace SysManage.Module.Article
{
    public partial class PartyArticleManageEdit : PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "PartyArticleAdd";
            }
        }

        public string ArticleModule
        {
            get
            {
                return this.Request["module"] ?? "";
            }
        }

        public string Category
        {
            get { return this.Request["Category"] ?? ""; }
        }
        #endregion

        #region 页面属性
        public string EditorContent
        {
            get
            {
                string id = GetQueryIntValue("id");
                if (!string.IsNullOrEmpty(id))
                {
                    PartyArticle article = DB.PartyArticles.Find(id);
                    return article.Content;
                }
                else
                {
                    return string.Empty;
                }
            }
        }
        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            //ShowNotify("触发了 Window1 的关闭事件！");
        }

        private void BindData()
        {
            if (Category != "")
                this.ddlCategory.Readonly = true;
            if (this.ArticleModule == SysEnum.ArticleModule.PartyBuildingWork.ToString())
            {
                ddlCategory.Hidden = false;
                ControlBusiness.ControlBindDataDictionary(ddlCategory, SysDataDictionary.PartyBuildingWork);
            }
            else if (this.ArticleModule == SysEnum.ArticleModule.InformationNewsletter.ToString())
            {
                ddlCategory.Hidden = false;
                ControlBusiness.ControlBindDataDictionary(ddlCategory, SysDataDictionary.InformationNewsletter, false, this.Category);
            }
            else if (this.ArticleModule == SysEnum.ArticleModule.ThreeAffairOpen.ToString())
            {
                ddlCategory.Hidden = false;
                ControlBusiness.ControlBindDataDictionary(ddlCategory, SysDataDictionary.ThreeAffairOpen, false, this.Category);
            }
            else if (this.ArticleModule == SysEnum.ArticleModule.PartyAffairs.ToString())
            {
                ddlCategory.Hidden = true;
                ControlBusiness.ControlBindDataDictionary(ddlCategory, SysDataDictionary.PartyAffairs, false, this.Category);
            }
            else
            {
                ddlCategory.Hidden = true;
            }
            ControlBusiness.ControlBindDataDictionary(rblFlags, "ZHDJ.Article.Flags");
            rblFlags.SelectedIndex = 0;
            ControlBusiness.ControlBindDataDictionary(ddlModule, SysDataDictionary.ArticleManagement, false, this.ArticleModule);

        }

        private void LoadData()
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            txtCreateTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
            string id = GetQueryIntValue("id");
            if (id != "")
            {
                PartyArticle article = DB.PartyArticles.Find(id);
                if (article == null)
                {
                    // 参数错误，首先弹出Alert对话框然后关闭弹出窗口
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }

                txtTitle.Text = article.Title;
                txtSubhead.Text = article.Subhead;
                txtAuthor.Text = article.Author;
                txtAuthorUrl.Text = article.AuthorUrl;
                txtArticlesLable.Text = article.ArticlesLable;
                rblFlags.SelectedValue = article.Flags.ToString();
                ddlModule.SelectedValue = article.Module;
                ddlCategory.SelectedValue = article.Category;
                txtSummary.Text = article.Summary;
                ppBranch.Value = article.BranchID;
                ppBranch.Text = ControlBusiness.GetBranchPickerText(article.BranchID);
                hdImageId.Text = article.ImageID;
                txtCreateTime.Text = Convert.ToDateTime(article.CreateTime).ToString("yyyy-MM-dd");
                if (!string.IsNullOrEmpty(hdImageId.Text))
                {
                    filePhoto.EmptyText = UpFileBusiness.GetFileName(hdImageId.Text);
                    HyperLink1.ImageID = hdImageId.Text;
                }

                string sql = string.Format(@"SELECT file.Title FROM tblpartyarticle as a
                                                INNER JOIN tblpartyarticlesfile as afile
                                                ON a.ID=afile.ArticleID
                                                LEFT JOIN tblpartyfile as file
                                                ON afile.FileID=file.ID
                                                WHERE a.ID='{0}';", article.ID);
                DataTable dt = ZHDJ.Data.MySqlHelper.ExecuteDataTable(sql);
                StringBuilder sb = new StringBuilder();
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append(dr["Title"]);
                    sb.Append(",");
                }
                if (sb.Length > 0)
                {
                    sb.Remove(sb.Length - 1, 1);
                }
                txtFilePath.Value = sb.ToString();
            }
            //设置组织动态页面,所属模块、所属组织属性
            if (ArticleModule == "Organizational" || ArticleModule == "WomenAndChildrenHome" || ArticleModule == "YouthMien" || ArticleModule == "UnionHome" || ArticleModule == "ZhengMinHuDong")
            {
                ppBranch.Value = this.CurrentUser.BranchID;//获取当前所属组织ID
                ppBranch.Text = ControlBusiness.GetBranchPickerText(this.CurrentUser.BranchID);//获取当前所属组织名称
                ppBranch.Enabled = false;//设置"所属组织"控件不可修改
                ddlModule.Hidden = true;//设置有下级菜单的所属模块隐藏
                ddlModule1.Hidden = false;//设置没有下级菜单的所属模块显示
                ddlModule1.Text = "组织动态";//设置"所属模块"文本
                ddlModule1.Enabled = false;//设置"所属模块"控件不可修改
            }
        }
        #endregion

        #region Events

        private void SaveData()
        {
            string id = GetQueryIntValue("id");
            string imageUrl = string.Empty;
            PartyArticle article;

            if (id != "")
            {
                //更新
                article = DB.PartyArticles.Find(id);
                if (article == null)
                {
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
                //先删除之前的文件数据
                DB.PartyArticlesFiles.Where(u => u.ArticleID == article.ID).ToList().ForEach(u => DB.PartyArticlesFiles.Remove(u));
                AddFile(article);
                //DB.SaveChanges();
            }
            else
            {
                article = new PartyArticle();
                article.ID = StringHelper.NewID;
                article.CreateBy = CurrentUser.LoginID;
                article.Status = 4;
                AddFile(article);

                DB.PartyArticles.Add(article);
            }

            article.Title = txtTitle.Text.Trim();
            article.Subhead = txtSummary.Text.Trim();
            article.Author = txtAuthor.Text.Trim();
            article.AuthorUrl = txtAuthorUrl.Text.Trim();
            article.Module = this.ArticleModule;
            article.ArticlesLable = txtArticlesLable.Text.Trim();
            article.Summary = txtSummary.Text.Trim();
            article.Flags = Convert.ToInt32(rblFlags.SelectedValue);
            if (ddlCategory.Items.Count > 0)
            {
                article.Category = ddlCategory.SelectedValue;
            }
            else
            {
                article.Category = Category;
            }
            article.BranchID = ppBranch.Value;
            article.Content = this.Request.Form["editorValue"];
            article.CreateTime = Convert.ToDateTime(txtCreateTime.Text);
            article.ModifyTime = DateTime.Now;
            article.ModifyBy = CurrentUser.LoginID;

            if (!string.IsNullOrEmpty(hdImageId.Text))
            {
                article.ImageID = hdImageId.Text;
            }

            DB.SaveChanges();
        }

        /// <summary>
        /// 保存并关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData();

            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            var rs = UpFileBusiness.Upload(filePhoto, CurrentUser.LoginID);
            if (rs.IsSuccess)
            {
                hdImageId.Text = rs.FileID;
                HyperLink1.ImageID = rs.FileID;
            }
        }

        private void AddFile(PartyArticle article)
        {
            string[] pathArray = txtFileID.Value.TrimEnd(',').Split(',');

            foreach (var item in pathArray)
            {
                PartyArticlesFile file = new PartyArticlesFile();
                file.ID = StringHelper.NewID;
                file.ArticleID = article.ID;
                file.FileID = item;
                file.FileType = 0;
                file.Status = 0;
                file.OrderNo = 0;
                file.CreateTime = DateTime.Now;
                file.CreateBy = CurrentUser.LoginID;
                file.ModifyBy = CurrentUser.LoginID;
                file.ModifyTime = DateTime.Now;

                DB.PartyArticlesFiles.Add(file);
            }
        }

        #endregion
    }
}